package com.wanmei.controller.product;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanmei.exception.WanmeiException;
import com.wanmei.pojo.*;
import com.wanmei.service.Impl.ProductpicServiceImpl;
import com.wanmei.service.ProductService;
import com.wanmei.util.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

@Controller
@RequestMapping("product")
public class ProductImgListController {
    @Autowired
    private ProductpicServiceImpl productpicService;
    @Autowired
    private ProductService productService;

    /**
     * 商品图片列表视图
     * @param pageNum 页码【可选】
     * @return
     */
    @RequestMapping("productImgListView")
    public ModelAndView addUserView(@RequestParam(value = "pageNum",defaultValue = "1")int pageNum) {
        //找出所有产品图片信息
        List<Product> productList = productpicService.findProductPicList();
        PageHelper.startPage(pageNum,10);// 分页
        //找出所有产品
        List<Product> products = productService.findAll();
        for (Product product: products) {
            for (Product pic: productList) {
                if (product.getPid().equals(pic.getPid())) {
                    product.setProductpicList(pic.getProductpicList());
                }
            }
        }

        PageInfo pageInfo = new PageInfo(products);
        ModelAndView model = new ModelAndView();
        model.addObject("pageInfo",pageInfo);
        model.addObject("productList",productList);
        model.setViewName("/product/productImgList");
        return model;
    }



    /**
     * public
     * 专门用来显示图片的接口
     */
    @RequestMapping("/showPic.do")
    public ResponseEntity<byte[]> showPicToJsp(@RequestParam("picid") int picid, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Productpic productpic = productpicService.selectAllByPicId(picid);
//      String realPath = productpic.getPicurl();
        if (productpic != null && !productpic.getPicurl().isEmpty()) {
            File file = new File(productpic.getPicurl());
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);
            return new ResponseEntity<byte[]>(Files.readAllBytes(file.toPath()), headers, HttpStatus.CREATED);
        }

        return null;
    }
    /**
     * public
     * 专门用来显示图片的接口
     */
    @RequestMapping("/showPic")
    public ResponseEntity<byte[]> showPicToJsps(@RequestParam("pid") int pid, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Productpic productpic = productpicService.selectOnePicUrl(pid);
//      String realPath = productpic.getPicurl();
        if (productpic != null && !productpic.getPicurl().isEmpty()) {
            File file = new File(productpic.getPicurl());
            System.out.println("");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);
            return new ResponseEntity<byte[]>(Files.readAllBytes(file.toPath()), headers, HttpStatus.CREATED);
        }

        return null;
    }

    /**
     * 富文本文件上传的图片：为了回显图片！
     */
    @RequestMapping("/uploadKindEditor.json")
    @ResponseBody
    public KindEditResult uploadPic(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest req) throws WanmeiException {
        KindEditResult kindEditResult = new KindEditResult();
        String realPath = req.getSession().getServletContext().getRealPath("/upload/");
        System.out.println("realPath+"+realPath);
        String fileName = file.getOriginalFilename();
        String newHeadName = ImageUtil.getImageNewName();
        //public String substring(int beginIndex) 返回一个新的字符串，它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始，直到此字符串末尾。
        String extensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (!extensionName.equals("png") && !extensionName.equals("jpg")) {
            throw new WanmeiException(Exception_Msg.ERROR_300001);
        }
        String newFileName = newHeadName + "." + extensionName;
        String path = realPath + newFileName;
        try {
            File file1 = new File(path);
            file.transferTo(file1);
            kindEditResult.setError(0);
            kindEditResult.setUrl("/upload/" + newFileName);
        } catch (IOException e) {
            e.printStackTrace();
            kindEditResult.setError(1);
            kindEditResult.setMessage("上传失败");
        }
        return kindEditResult;
    }



}
